03 / 04

Write code to explain higher-order function

All examples of map,reduce, filter, currying and functions with callbacks are examples of HOC.

javascript
Difficulty: 6/10
Topics: callbacks, function composition, async utilities

Scenario Questions

0-2 years experience
  1. 1

    We have an array of numbers and need to double each value. Write a function that takes a callback to apply the transformation. How would you implement it using a higher‑order function?

  2. 2

    Suppose you need to filter a list of users based on a predicate you’ll receive at runtime. Show how you'd write a higher‑order function that returns the filtered list.

2-5 years experience
  1. 1

    Your team added a utility mapAsync that takes an array and an async callback, but it's causing unhandled promise rejections in production. Walk me through how you'd debug it and what changes you'd make.

  2. 2

    We want to create a reusable withLogging wrapper that logs entry and exit of any async function. Explain how you'd implement it and discuss any trade‑offs regarding error handling.

5-8 years experience
  1. 1

    We're building a plugin architecture where plugins can register middleware functions that transform request objects. Design a higher‑order function that composes these middleware functions efficiently, considering order and error propagation.

  2. 2

    A performance hotspot was identified in a data‑processing pipeline that uses many nested higher‑order functions. How would you refactor it to improve throughput while preserving composability?

8+ years experience
  1. 1

    Our legacy codebase heavily uses callbacks for async flow, and we want to migrate to a promise‑based approach using higher‑order utilities. Outline a migration strategy that minimizes risk across multiple teams.

  2. 2

    Discuss the architectural implications of exposing a public API that allows customers to supply their own higher‑order functions for customizing business logic. How would you enforce safety, versioning, and performance guarantees?

Follow-up Questions

  • What happens if the callback throws an error?
  • How would you preserve the `this` context inside the higher‑order function?
  • Can you compare the memory impact of chaining versus composing functions?